package com.legoo.studaychineseonline.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.InputType;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.gson.Gson;
import com.legoo.studaychineseonline.R;
import com.legoo.studaychineseonline.base.BaseActivity;
import com.legoo.studaychineseonline.bean.InfoBean;
import com.legoo.studaychineseonline.http.API;
import com.legoo.studaychineseonline.http.XUtil;
import com.legoo.studaychineseonline.utils.ImageUtil;
import com.legoo.studaychineseonline.utils.IsNetWork;
import com.legoo.studaychineseonline.utils.RegularUtil;
import com.legoo.studaychineseonline.view.MyCommonPopupWindow;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 用户信息
 */
public class UserInfoActivity extends BaseActivity implements MyCommonPopupWindow.ViewInterface {
    @BindView(R.id.tv_title_left)
    TextView tvTitleLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_title_right)
    TextView tvTitleRight;
    @BindView(R.id.iv_pic)
    ImageView ivPic;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.ll_tou)
    LinearLayout llTou;
    @BindView(R.id.ll_nickname)
    LinearLayout llNickname;
    @BindView(R.id.ll_email)
    LinearLayout llEmail;
    @BindView(R.id.ll_password)
    LinearLayout llPassword;
    @BindView(R.id.ll_sex)
    LinearLayout llSex;
    @BindView(R.id.ll_age)
    LinearLayout llAge;
    @BindView(R.id.bt_out)
    Button btOut;
    @BindView(R.id.tv_nick_name)
    TextView tvNickName;
    @BindView(R.id.tv_email)
    TextView tvEmail;
    @BindView(R.id.tv_sex)
    TextView tvSex;
    @BindView(R.id.tv_age)
    TextView tvAge;
    private PopupWindow mPopupWindow;
    private TextView popTitle;
    private TextView popShuoMing;
    private EditText shuRu;
    private Button btSure;
    private ImageView ivDismiss;
    private String clickType;
    private String popNeiRong;

    @Override
    protected void myOnCreate(@Nullable Bundle savedInstanceState) {
        ButterKnife.bind(this);
        tvTitle.setText("用户信息");
        tvTitleRight.setVisibility(View.INVISIBLE);
        tvTitleLeft.setBackgroundResource(R.mipmap.img_fanhui);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (IsNetWork.isNetworkAvailable(context)){
            showProgressDialog();
            getUserInfo();
        }else {
            showToast("请检查你的网络是否异常");
        }

    }


    @Override
    protected void initData() {

    }

    @Override
    protected void resolveBundle(Bundle bundle) {

    }

    @Override
    protected int myLayoutId() {
        return R.layout.activity_user;
    }


    @OnClick({R.id.tv_title_left, R.id.iv_pic, R.id.ll_nickname, R.id.ll_email, R.id.ll_password, R.id.ll_sex, R.id.ll_age, R.id.bt_out})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_title_left:
                break;
            case R.id.iv_pic:
                PictureSelector.create(this)
                        .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
//                .theme()//主题样式(不设置为默认样式) 也可参考demo values/styles下 例如：R.style.picture.white.style
//                        .maxSelectNum(1)// 最大图片选择数量 int
//                .minSelectNum()// 最小选择数量 int
                        .imageSpanCount(4)// 每行显示个数 int
                        .selectionMode(PictureConfig.SINGLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                        .previewImage(false)// 是否可预览图片 true or false
//                        .previewVideo(false)// 是否可预览视频 true or false
//                        .enablePreviewAudio(false) // 是否可播放音频 true or false
                        .isCamera(true)// 是否显示拍照按钮 true or false
                        .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                        .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                        .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                        .setOutputCameraPath("/CustomPath")// 自定义拍照保存路径,可不填
                        .enableCrop(false)// 是否裁剪 true or false
                        .compress(true)// 是否压缩 true or false
//                .glideOverride()// int glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
//                .withAspectRatio()// int 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
//                .hideBottomControls()// 是否显示uCrop工具栏，默认不显示 true or false
//                .isGif()// 是否显示gif图片 true or false
//                .compressSavePath(getPath())//压缩图片保存地址
//                .freeStyleCropEnabled()// 裁剪框是否可拖拽 true or false
//                .circleDimmedLayer()// 是否圆形裁剪 true or false
//                .showCropFrame()// 是否显示裁剪矩形边框 圆形裁剪时建议设为false   true or false
//                .showCropGrid()// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
//                .openClickSound()// 是否开启点击声音 true or false
//                .selectionMedia()// 是否传入已选图片 List<LocalMedia> list
//                .previewEggs()// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
                        .cropCompressQuality(50)// 裁剪压缩质量 默认90 int
                        .minimumCompressSize(100)// 小于100kb的图片不压缩
                        .synOrAsy(true)//同步true或异步false 压缩 默认同步
//                .cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效 int
//                .rotateEnabled() // 裁剪是否可旋转图片 true or false
//                .scaleEnabled()// 裁剪是否可放大缩小图片 true or false
//                .videoQuality()// 视频录制质量 0 or 1 int
//                .videoMaxSecond(15)// 显示多少秒以内的视频or音频也可适用 int
//                .videoMinSecond(10)// 显示多少秒以内的视频or音频也可适用 int
//                .recordVideoSecond()//视频秒数录制 默认60s int
//                .isDragFrame(false)// 是否可拖动裁剪框(固定)
                        .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
                break;
            case R.id.ll_nickname:
                clickType = "0";
                showPopWindow();
                break;
            case R.id.ll_email:
                clickType = "1";
                showPopWindow();
                break;
            case R.id.ll_password:
                break;
            case R.id.ll_sex:
                selectSex(view);
                break;
            case R.id.ll_age:
                clickType = "2";
                showPopWindow();
                break;
            case R.id.bt_out:
                break;
            default:

        }
    }

    /*调用完系统相机和相册后的结果*/
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
//                    File file = new File(selectList.get(0).getCompressPath());
                    String path = selectList.get(0).getCompressPath();
                    showProgressDialog();
                    changeUserPic(path);
                    break;
                default:
            }
        }
    }

    public void showPopWindow() {

        if (mPopupWindow != null && mPopupWindow.isShowing()) {
            return;
        }
        mPopupWindow = new MyCommonPopupWindow.Builder(this)
                .setView(R.layout.popup_user_info)
                .setWidthAndHeight(600, ViewGroup.LayoutParams.WRAP_CONTENT)
                .setViewOnclickListener(this)
                .setOutsideTouchable(false)
                .setBackGroundLevel((float) 0.5)
                .create();
        mPopupWindow.setBackgroundDrawable(null);
        mPopupWindow.setFocusable(true);
        mPopupWindow.showAtLocation(this.getWindow().getDecorView(), Gravity.CENTER, 0, 0);
        //mPopupWindow.showAsDropDown(ivPic);

    }

    @Override
    public void getChildView(View view, int layoutResId) {
        switch (layoutResId) {
            case R.layout.popup_user_info:
                popTitle = view.findViewById(R.id.tv_title);
                popShuoMing = view.findViewById(R.id.tv_shuoming);
                shuRu = view.findViewById(R.id.et_shuru);
                shuRu.clearFocus();

                btSure = view.findViewById(R.id.bt_sure);
                ivDismiss = view.findViewById(R.id.iv_dismiss);
                if ("0".equals(clickType)) {
                    shuRu.setInputType(InputType.TYPE_CLASS_TEXT);
                    popTitle.setText("修改用户名");
                    popShuoMing.setText("用户名 :");

                }
                if ("1".equals(clickType)) {
                    shuRu.setInputType(InputType.TYPE_CLASS_TEXT);
                    popTitle.setText("修改邮箱");
                    popShuoMing.setText("邮箱 :");
                }
                if ("2".equals(clickType)) {
                    shuRu.setInputType(InputType.TYPE_CLASS_NUMBER);
                    popTitle.setText("修改年龄");
                    popShuoMing.setText("年龄 :");
                }
                btSure.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        popNeiRong = shuRu.getText().toString().trim();
                        if ("".equals(popNeiRong)) {
                            showToast("输入内容不能为空");
                            return;
                        }
                        if ("0".equals(clickType)) {
                            int length = popNeiRong.length();
                            if (length<6||length>30){
                                showToast("昵称长度请保持在6-30字数之间");
                                return;
                            }else {
                                changeUserInfo(popNeiRong,"","","","");
                            }

                        }
                        if ("1".equals(clickType)) {
                            if (!RegularUtil.isEmail(popNeiRong)){
                                showToast("请输入正确格式的邮箱");
                                return;
                            }else {
                                changeUserInfo("","",popNeiRong,"","");
                            }

                        }
                        if ("2".equals(clickType)) {
                            int i = Integer.parseInt(popNeiRong);
                            if (i>=0&&i<200){
                                changeUserInfo("","","","",popNeiRong);
                            }else {
                                showToast("请输入正确的年龄数值");
                            }
                        }
                    }
                });
                ivDismiss.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (mPopupWindow != null) {
                            mPopupWindow.dismiss();
                        }
                    }
                });
                break;
            default:
        }
    }

    public void selectSex(View v) {
        final View view = v;
        final String[] items = new String[]{"男", "女"};
        new AlertDialog.Builder(UserInfoActivity.this).setTitle("选择").setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0:
                        changeUserInfo("","","","m","");
                        break;
                    case 1:
                        changeUserInfo("","","","f","");
                        break;
                    default:
                }
            }
        }).show();
    }

    /**
     * 修改个人信息
     */
    private void changeUserInfo(String nickname, String phone, String email, String sex, String age) {
        Map<String, Object> map = new HashMap<>();
        map.put("access_token",API.TOKEN);
        if (null != nickname && !"".equals(nickname)) {
            map.put("nickname", nickname);
        }
        if (null != phone && !"".equals(phone)) {
            map.put("phone", phone);
        }
        if (null != email && !"".equals(email)) {
            map.put("email", email);
        }
        if (null != sex && !"".equals(sex)) {
            map.put("sex", sex);
        }
        if (null != age && !"".equals(age)) {
            map.put("age", age);
        }

        XUtil.Post(API.CHANGE, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 修改头像
     */
    private void changeUserPic(String path) {
        RequestParams params = new RequestParams(API.CHANGE);
        params.setMultipart(true);
        params.addBodyParameter("icon", new File(path), "multipart/form-data");
        params.addBodyParameter("access_token", API.TOKEN);
        Callback.Cancelable cancelable = x.http().post(params, new Callback.ProgressCallback<String>() {
            @Override
            public void onSuccess(String result) {
                hideProgressDialog();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                hideProgressDialog();
                showToast("修改失败");

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }

            @Override
            public void onWaiting() {

            }

            @Override
            public void onStarted() {

            }

            @Override
            public void onLoading(long total, long current, boolean isDownloading) {

            }
        });
    }

    /**
     * 获取用户信息
     */
    private void getUserInfo() {
        Map<String, Object> map = new HashMap<>();
        map.put("access_token",API.TOKEN);
        XUtil.Post(API.INFO, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                InfoBean infoBean = new Gson().fromJson(result, InfoBean.class);
                if (infoBean.getCode() == API.HTTP_OK) {
                    tvAge.setText( infoBean.getData().getClient().getAge());
                    tvEmail.setText(infoBean.getData().getClient().getEmail());
                    tvNickName.setText(infoBean.getData().getClient().getAge());
                    if ("f".equals(infoBean.getData().getClient().getSex())){
                        tvSex.setText("女");
                    }else {
                        tvSex.setText("男");
                    }
                    if (!"".equals(infoBean.getData().getClient().getIcon())){
                        new ImageUtil().setCircleImg(ivPic,infoBean.getData().getClient().getIcon());
                    }
                    API.USER_ID = infoBean.getData().getClient().getId();

                }
                hideProgressDialog();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                hideProgressDialog();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


}
